<template>
  <ex-dialog width="1200px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" :label-width="labelWidth"
      class="demo-ruleForm">
      <div class="from_title">活动基本信息</div>
      <el-form-item label="活动名称" prop="name">
        <el-input type="text" maxlength="50" v-model="ruleForm.name" autocomplete="off" placeholder="请填写活动名称"
          :style="{width: inputWidth}">
        </el-input>
      </el-form-item>
      <el-form-item label="活动时间：" prop="date" ref="timeRef">
        <el-date-picker v-model="ruleForm.date" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          :clearable="false" @input="$forceUpdate()" :style="{width: inputWidth}" :disabled="ruleForm.id!=''&&ruleForm.status!=1?true:false">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="shopLs">
        <el-select v-model="ruleForm.shopLs" placeholder="请选择" multiple filterable :style="{width: inputWidth}"
          value-key="id" @change="shopChange">
          <el-option v-for="item in optionsShop" :key="item.id" :label="item.value" :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-table v-loading="tableLoading" :data="tableList" stripe border>
          <el-table-column label="序号" type="index" width="55" align="center" fixed />
          <el-table-column label="商户账号名称" align="center" prop="merchantName" />
          <el-table-column label="店铺名称" align="center" prop="shopName" />
          <el-table-column label="行业类型" align="center" prop="shopTypeName" />
          <el-table-column label="神椰行业" align="center" prop="industryName" />
          <el-table-column label="发行方" align="center" prop="issuerName" />
          <el-table-column label="赚卡数量（种类）" align="center" prop="cardNum" width="180px" />
          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="deleteClick(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <div class="from_title">分红池累加规则</div>
      <el-form-item label="分红奖金累加规则：" prop="addUpType">
        <el-select v-model="ruleForm.addUpType" filterable placeholder="请选择" :style="{width: inputWidth}"
          @change="ruleForm.addUpAmount=''">
          <el-option v-for="item in addUpTypeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="累加比例：" prop="addUpAmount" v-if="ruleForm.addUpType=='1'">
        <el-input type="text" v-model="ruleForm.addUpAmount" autocomplete="off" placeholder="请填写"
          :style="{width: inputWidth}">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="累加数额：" prop="addUpAmount" v-if="ruleForm.addUpType=='2'">
        <el-input type="text" v-model="ruleForm.addUpAmount" autocomplete="off" placeholder="请填写"
          :style="{width: inputWidth}">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <div class="from_title">分红池分红规则</div>
      <el-form-item label="分红资金类型：" prop="bonusType">
        <el-select v-model="ruleForm.bonusType" filterable placeholder="请选择" :style="{width: inputWidth}" :disabled="ruleForm.id!=''&&ruleForm.status!=1?true:false">
          <el-option v-for="item in bonusTypeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="from_title">分红池分红周期</div>
      <el-form-item label="分红周期：" prop="bonusCycle">
        <el-input type="text" v-model="ruleForm.bonusCycle" autocomplete="off" placeholder="请填写" :disabled="ruleForm.id!=''&&ruleForm.status!=1?true:false"
          :style="{width: inputWidth}">
          <template slot="append">天</template>
        </el-input>
      </el-form-item>
      <div class="from_title">分红池分红计算规则</div>
      <el-form-item label="周期消费金额占比：" prop="consumeCycleRatio">
        <el-input type="text" v-model="ruleForm.consumeCycleRatio" autocomplete="off" placeholder="请填写"
          :style="{width: inputWidth}">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="财富值占比：" prop="wealthRatio">
        <el-input type="text" v-model="ruleForm.wealthRatio" autocomplete="off" placeholder="请填写"
          :style="{width: inputWidth}">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <div style="font-size: 12px;color:red;padding-top:10px">
        分红公式：用户获得分红金额=分红池金额*[（用户周期内消费金额/平台周期消费总金额*消费金额占比a%）+（当前用户财富值/当前参与分红用户的总财富值*财富值占比b%）]  注意：a%+b%=100%</div>
      <div class="from_title">玩法规则</div>
      <el-form-item label="" prop="" ref="gameRulesRef">
        <ImageUploadMore :limit="1" :fileSize="20" @successImg="getGameRules" :value="ruleForm.gameRules">
        </ImageUploadMore>
      </el-form-item>
      <el-form-item style="margin-top: 60px">
        <el-button type="warning" @click="submitForm('ruleForm',1)" :loading="loading" v-if="ruleForm.status==1||ruleForm.id==''">保存草稿</el-button>
        <el-button type="primary" @click="submitForm('ruleForm',2)" :loading="loading">保存提交</el-button>
        <el-button @click="handleClose('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </ex-dialog>
</template>
<script>
  // components
  import Loading from '@/components/Loading/index'
  // api
  import {
    shopSelect,
    poolShop,
    addPool,
    poolDetail,
    editPool,
  } from '@/api/consumeMiningManagement/dividendPools'

  export default {
    components: {
      Loading
    },
    props: {
      visible: Boolean,
      id: String,
      pathType: String,
    },
    data() {
      var checkAddUpAmount = (rule, value, callback) => { //累加比例/累加数额校验
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请填写大于0且最多保留两位小数的数值'));
        } else {
          return callback()
        }
      };
      var checkBonusCycle = (rule, value, callback) => { //分红周期校验
        let regNumber = /^((?!0)\d{1,2}|100)$/; //1到100的正整数
        if (regNumber.test(value) == false) {
          return callback(new Error('请填写1到100的正整数'));
        } else {
          return callback()
        }
      };
      var checkConsumeCycleRatio = (rule, value, callback) => { //周期消费金额占比校验
        let regNumber = /^([0-9]{1,2}|100)$/; //0到100的正整数
        if (regNumber.test(value) == false) {
          return callback(new Error('请填写0到100的正整数'));
        } else {
          return callback()
        }
      };
      var checkWealthRatio = (rule, value, callback) => { //财富值占比校验
        let regNumber = /^([0-9]{1,2}|100)$/; //0到100的正整数
        if (regNumber.test(value) == false) {
          return callback(new Error('请填写0到100的正整数'));
        } else {
          return callback()
        }
      };
      return {
        labelWidth: '150px',
        inputWidth: '420px',
        loading: false,
        title: '新增/编辑分红池活动',
        bonusTypeList: [{
          id: '1',
          value: 'CoCo'
        }, {
          id: '2',
          value: '椰分'
        }],
        addUpTypeList: [{
            id: '1',
            value: '交易金额比例'
          },
          {
            id: '2',
            value: '固定金额'
          },
        ],
        tableLoading: false,
        tableList: [],
        optionsShop: [], //店铺列表
        action: process.env.VUE_APP_BASE_API + "/common/v1/upload",
        imgLoading: false,
        ruleForm: {
          status:'',//状态 1 草稿 2 待开始 3 进行中 4 已结束
          date: [], //活动时间（校验用）
          addUpAmount: '', //累加比例/累加数额
          addUpType: '', //累加规则 1 交易金额比例 2 固定金额
          bonusCycle: '', //分红周期（天）
          bonusType: '', //分红资金类型 1 神椰Coco 2 椰分
          consumeCycleRatio: '', //周期消费金额占比（%）
          startTime: '', //活动开始时间
          endTime: '', //活动结束时间
          gameRules: '', //玩法规则
          id: '', //分红池id（编辑必填）
          name: '', //活动名称
          wealthRatio: '', //财富值占比（%）
          saveStatus: '', //保存状态 1 保存草稿 2 保存提交
          shopLs: [],
          shopList: [ //店铺列表
            {
              cardNum: '', //赚卡数量（种类）
              industryName: '', //神椰行业
              issuerName: '', //发行方
              merchantId: '', //商家id
              merchantName: '', //商户账号名称
              shopName: '', //店铺名称
              shopTypeName: '', //行业类型
            }
          ],
        },
        flags: false,
        rules: {
          name: [{
            required: true,
            message: '请填写活动名称',
            trigger: ['blur', 'change']
          }],
          date: [{
            type: 'array',
            required: true,
            message: '请选择活动时间',
            trigger: 'change'
          }, ],
          addUpType: [{
            required: true,
            message: '请选择分红奖金累加规则',
            trigger: ['blur', 'change']
          }],
          addUpAmount: [{
            required: true,
            // message: '请输入',
            validator: checkAddUpAmount,
            trigger: ['blur', 'change']
          }],
          bonusType: [{
            required: true,
            message: '请选择分红资金类型',
            trigger: ['blur', 'change']
          }],
          bonusCycle: [{
            required: true,
            // message: '请输入分红周期',
            validator: checkBonusCycle,
            trigger: ['blur', 'change']
          }],
          consumeCycleRatio: [{
            required: true,
            // message: '请输入周期消费金额占比',
            validator: checkConsumeCycleRatio,
            trigger: ['blur', 'change']
          }],
          wealthRatio: [{
            required: true,
            // message: '请输入财富值占比',
            validator: checkWealthRatio,
            trigger: ['blur', 'change']
          }],
          shopLs: [{
            required: true,
            message: "请选择店铺",
            trigger: ['blur', 'change'],
          }],
          // minBetAmount: [{
          //   required: true,
          //   validator: validateMinBetAmount,
          //   trigger: 'blur'
          // }],

        }
      }
    },
    computed: {

    },
    created() {
      this.getShopSelect()
      if (this.pathType == 'edit') {
        this.title = '编辑分红池活动'
        this.getDetail()
      } else if (this.pathType == 'add') {
        this.ruleForm.id = ''
        this.title = '新增分红池活动'
      }

    },
    methods: {
      // 获取店铺列表
      getShopSelect() {
        let data = {
          merchantIdList: []
        }
        shopSelect(data).then(res => {
          this.optionsShop = res.result
        })
      },
      //查询店铺信息
      getPoolShop(list) {
        let data = {
          merchantIdList: list
        }
        this.tableLoading = true
        poolShop(data).then(res => {
          this.tableList = res.result
          this.tableLoading = false
          this.ruleForm.shopList = this.tableList
        }).catch(() => {
          this.tableLoading = false
        })
      },
      //店铺选择
      shopChange(e) {
        console.log(e)
        this.ruleForm.shopLs = e
        let arr = [];
        this.ruleForm.shopLs.forEach(e => {
          arr.push(e.id)
        })
        if (arr.length > 0) {
          this.getPoolShop(arr)
        } else {
          this.tableList = []
        }
        // this.ruleForm.shopList = this.tableList
        // console.log('this.tableList',this.tableList)
        // console.log('this.ruleForm.shopList',this.ruleForm.shopList)
      },
      // 删除
      deleteClick(item) {
        console.log(item.merchantId)
        let list = this.ruleForm.shopLs
        var deleteList = this.filterArr(list, item.merchantId);
        this.ruleForm.shopLs = deleteList
        let arr = [];
        this.ruleForm.shopLs.forEach(e => {
          arr.push(e.id)
        })
        if (arr.length > 0) {
          this.getPoolShop(arr)
        } else {
          this.tableList = []
        }
        // this.ruleForm.shopList = this.tableList
        // console.log('this.ruleForm.shopList',this.ruleForm.shopList)
      },
      //删除对应id数组
      filterArr(list, id) {
        list = list.filter(item => item.id !== id)
        return list
      },
      //规则图片
      getGameRules(e) {
        this.ruleForm.gameRules = e
        this.$refs['gameRulesRef'].clearValidate();
      },
      //活动详情
      getDetail() {
        var id = this.id
        poolDetail(id).then(res => {
          // this.ruleForm = res.result
          this.tableList = res.result.shopList
          let newarr = []
         this.optionsShop.map(item => {
            this.tableList.map(list => {
              if (item.id === list.merchantId) {
                newarr.push({
                  id: list.merchantId,
                  data:'',
                  additionalValue: '',
                  value: list.shopName
                })
              }
            })
          })
          console.log('333', newarr);
            this.ruleForm.status = res.result.status
            this.ruleForm.date = [res.result.startTime,res.result.endTime] //活动时间（校验用）
            this.ruleForm.addUpAmount = res.result.addUpAmount //累加比例/累加数额
            this.ruleForm.addUpType = res.result.addUpType //累加规则 1 交易金额比例 2 固定金额
            this.ruleForm.bonusCycle = res.result.bonusCycle //分红周期（天）
            this.ruleForm.bonusType = res.result.bonusType //分红资金类型 1 神椰Coco 2 椰分
            this.ruleForm.consumeCycleRatio = res.result.consumeCycleRatio //周期消费金额占比（%）
            this.ruleForm.startTime = res.result.startTime //活动开始时间
            this.ruleForm.endTime = res.result.endTime //活动结束时间
            this.ruleForm.gameRules = res.result.gameRules //玩法规则
            this.ruleForm.id = res.result.id//分红池id（编辑必填）
            this.ruleForm.name = res.result.name //活动名称
            this.ruleForm.wealthRatio = res.result.wealthRatio //财富值占比（%）
            this.ruleForm.saveStatus = res.result.saveStatus //保存状态 1 保存草稿 2 保存提交
            this.ruleForm.shopLs = newarr
            this.ruleForm.shopList = res.result.shopList
        })
      },
      //保存
      submitForm(formName, type) {
        console.log('formName', formName)
        this.$refs[formName].validate((valid) => {
          console.log('valid', valid)
          if (valid) {
            this.ruleForm.saveStatus = type
            this.ruleForm.startTime = this.ruleForm.date[0]
            this.ruleForm.endTime = this.ruleForm.date[1]
            this.loading = true
            if (this.pathType == 'add') {
              var data = {
                ...this.ruleForm
              }
              addPool(data).then(res => {
                this.handleSuccess("保存成功")
                setTimeout(() => {
                  this.handleClose()
                  this.loading = false
                }, 1000);
              }).catch(() => {
                this.loading = false
              })
            } else if (this.pathType == 'edit') {
              var data = {
                ...this.ruleForm
              }
              editPool(data).then(res => {
                this.handleSuccess("修改成功")
                setTimeout(() => {
                  this.handleClose()
                  this.loading = false
                }, 1000);
              }).catch(() => {
                this.loading = false
              })
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      //取消
      handleClose(formName) {
        this.$emit('update:visible', false)
        // this.$refs[formName].resetFields();
      },
      //确认
      handleSuccess(msg) {
        this.$message.success(msg);
        this.$emit('success')
      },
    }
  }

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 130px;
    height: 130px;
    text-align: center;
    line-height: 130px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 130px;
    height: 130px;
  }

  .el-input {
    width: 300px;
  }

  .from_title {
    color: #1890ff;
    font-size: 15px;
    border-bottom: 1px solid #ddd;
    padding: 20px 0 10px;
    margin-bottom: 20px;
  }

</style>
